<template>
    <div class="app-container" id='editGoods'>
      <!-- 商品介绍卡片 -->
      <el-card class="box-card">
        <h3>商品介绍</h3>
        <el-form ref="dataForm"  :model="dataForm" label-width="120px" size="mini"
          style="width: 800px;margin-left: 20px;">
          <el-form-item label="商品编号" prop="goodsSn">
            <el-input v-model="dataForm.goodsSn"></el-input>
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="dataForm.name"></el-input>
          </el-form-item>
          <el-form-item label="专柜价格" prop="counterPrice">
            <el-input v-model="dataForm.counterPrice">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="当前价格" prop="retailPrice">
            <el-input v-model="dataForm.retailPrice">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="是否新品" prop="isNew">
            <el-radio-group v-model="dataForm.isNew">
              <el-radio :label="true">新品</el-radio>
              <el-radio :label="false">非新品</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否热卖" prop="isHot">
            <el-radio-group v-model="dataForm.isHot">
              <el-radio :label="true">热卖</el-radio>
              <el-radio :label="false">普通</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否在售" prop="isOnSale">
            <el-radio-group v-model="dataForm.isOnSale">
              <el-radio :label="true">在售</el-radio>
              <el-radio :label="false">未售</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="商品图片" prop="picUrl">
            <el-upload class="avatar-uploader" :action="uploadPath" :headers="headers" :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="dataForm.picUrl" :src="dataForm.picUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="宣传画廊" prop="picUrl">
            <el-upload class="avatar-uploader" :action="uploadPath" :limit="5" :headers="headers" list-type="picture-card" :file-list="galleryFileList"
              :on-remove="handleRemove" :on-success="handleGalleryUrl">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品单位" prop="unit">
            <el-input v-model="dataForm.unit" placeholder="件 / 个 / 盒"></el-input>
          </el-form-item>
          <el-form-item label="关键字" prop="keywords">
            <el-tag v-for="tag in keywords" :key="tag" closable type="primary" @close="handleClose(tag)">{{tag}}</el-tag>
            <el-input v-if="newKeywordVisible" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm"
              ref="newKeywordInput" v-model="newKeyword" class="input-new-keyword"></el-input>
            <el-button v-else class="button-new-keyword" type="primary" @click="showInput">+ 增加</el-button>
          </el-form-item>
          <el-form-item label="所属分类" prop="categoryId">
            <el-cascader clearable placeholder="试试搜索：指南" :options="categoryList" expand-trigger="hover" filterable @click="handleCategoryGhange">
            </el-cascader>
          </el-form-item>
          <el-form-item label="所属品牌商" prop="brandId">
            <el-select v-model="dataForm.brandId">
              <el-option v-for="item in brandList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品简介" prop="brief">
            <el-input v-model="dataForm.brief"></el-input>
          </el-form-item>
          <el-form-item label="商品详情介绍" prop="detail">
            <editor :init="editorInit" v-model="dataForm.detail"></editor>
          </el-form-item>
        </el-form>
      </el-card>
      <!-- 商品规格卡片 -->
      <el-card class="box-card">
        <h3>商品规格</h3>
        <el-row :gutter="20" type="flex" align="middle" style="padding: 20px 0">
          <el-col :span="10">
            <el-radio-group v-model="multipleSpec" @change="specChange">
              <el-radio-button :label="false">默认标准规格</el-radio-button>
              <el-radio-button :label="true">多规格支持</el-radio-button>
            </el-radio-group>
          </el-col>
          <el-col :span="10" v-if="multipleSpec">
            <el-button plain type="primary" @click="handleSpecificationShow">添加</el-button>
          </el-col>
        </el-row>
        <el-table :data="specifications" style="width: 100%">
          <el-table-column prop="specification" label="规格名">
          </el-table-column>
          <el-table-column prop="value" label="规格值">
            <template slot-scope="scope">
              <el-tag type="primary">{{scope.row.value}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="规格图片">
            <template slot-scope="scope">
              <img v-if="scope.row.picUrl" :src="scope.row.picUrl" width="40">
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" v-if="multipleSpec">
            <template slot-scope="scope">
              <el-button @click="specificationsDelete(scope.row)" type="danger" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 商品库存卡片 -->
      <el-card class="box-card">
          <h3>商品库存</h3>
          <el-table :data="products" style="width: 100%">
              <el-table-column prop="value" label="货品规格">
                <template slot-scope="scope">
                  <el-tag type="primary" v-for="tag in scope.row.specifications" :key="tag">{{tag}}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="price" label="货品售价" width="100">
              </el-table-column>
              <el-table-column prop="number" label="货品数量" width="100">
              </el-table-column>
              <el-table-column prop="url" label="货品图片" width="100">
                <template slot-scope="scope">
                  <img v-if="scope.row.url" :src="scope.row.url" width="40">
                </template>
              </el-table-column>
              <el-table-column align="center" fixed="right" label="操作" width="100">
                <template slot-scope="scope">
                  <el-button @click="handleProductShow(scope.row)" type="primary" size="small">设置</el-button>
                </template>
              </el-table-column>
            </el-table>
      </el-card>
      <!-- 商品参数卡片 -->
      <el-card class="box-card">
          <h3>商品参数</h3>
          <el-button plain type="primary" @click="handleAttributeShow">添加</el-button>
          <el-table :data="attributes" style="width: 100%">
              <el-table-column prop="attribute" label="商品参数名称">
              </el-table-column>
              <el-table-column prop="value" label="商品参数值">
              </el-table-column>
              <el-table-column align="center" fixed="right" label="操作">
                <template slot-scope="scope">
                  <el-button @click="handleAttributeDelete(scope.row)" type="danger" size="small">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
      </el-card>
      <!-- 提交商品上架 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="createData">确定</el-button>
      </div>
      <!-- 设置规格模态框 -->
      <el-dialog title="设置规格" :visible.sync="specVisible" width="60%">
        <el-form ref="specForm" :rules="specRules" :model="specForm" label-width="100px" size="mini"
          style="width: 400px;margin-left: 20px;">
          <el-form-item label="规格名" prop="specification">
            <el-input v-model="specForm.specification"></el-input>
          </el-form-item>
          <el-form-item label="规格值" prop="value">
            <el-input v-model="specForm.value"></el-input>
          </el-form-item>
          <el-form-item label="规格图片" prop="picUrl">
            <el-upload class="avatar-uploader" :action="uploadPath" :headers="headers" :show-file-list="false"
              :on-success="handleSpecSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="specForm.picUrl" :src="specForm.picUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="specVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSpecificationAdd">确定</el-button>
        </div>
      </el-dialog>
      <!-- 设置货品模态框 -->
      <el-dialog title="设置货品" :visible.sync="productVisiable" width="60%">
        <el-form ref="productForm"  :model="productForm" label-width="100px" size="mini"
          style="width: 400px;margin-left: 20px;">
          <el-form-item label="货品规格列" prop="specifications">
            <el-tag v-for="tag in productForm.specifications" :key="tag">{{tag}}</el-tag>
          </el-form-item>
          <el-form-item label="货品售价" prop="price">
            <el-input v-model="productForm.price"></el-input>
          </el-form-item>
          <el-form-item label="货品数量" prop="number">
            <el-input v-model="productForm.number"></el-input>
          </el-form-item>
          <el-form-item label="货品图片" prop="url">
            <el-upload class="avatar-uploader" :action="uploadPath" :headers="headers" :show-file-list="false"
              :on-success="handleProductSuccess">
              <img v-if="productForm.url" :src="productForm.url" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="productVisiable = false">取消</el-button>
          <el-button type="primary" @click="handleProductEdit">确定</el-button>
        </div>
      </el-dialog>
      <!-- 设置商品参数模态框 -->
      <el-dialog title="设置商品参数" :visible.sync="attributeVisiable" width="60%">
        <el-form ref="attributeForm"  :model="attributeForm" label-width="100px" size="mini"
          style="width: 400px;margin-left: 20px;">
          <el-form-item label="商品参数名称" prop="attribute">
            <el-input v-model="attributeForm.attribute"></el-input>
          </el-form-item>
          <el-form-item label="商品参数值" prop="value">
            <el-input v-model="attributeForm.value"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="attributeVisiable = false">取消</el-button>
          <el-button type="primary" @click="handleAttributeAdd">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  <script>
    import Pagination from '@/components/Pagination'
    import Editor from '@tinymce/tinymce-vue'
    import {
      addSubject,
      uploadPath,
      createStorage
    } from '@/api/activity/subject'
    import {
      listCatAndBrand,
      listGoods,
      editGoods,
      detailGoods
    } from '@/api/goods/goods'
    import {
      getToken
    } from '@/utils/auth'
    export default {
      name: 'editGoods',
      components: {
        Pagination,
        Editor
      },
      computed: {
        headers() {
          return {
            'Shopping-Admin-Token': getToken()
          }
        }
      },
      data() {
        return {
          uploadPath,
          //新增表单数据
          dataForm: {
            id: '',
            goodsSn: '',
            name: '',
            counterPrice: '',
            retailPrice: '',
            isNew: true,
            isHot: false,
            isOnSale: false,
            picUrl: '',
            gallery: [],
            unit: '',
            keywords: '',
            price: '',
            goods: []
          },
          //图片列表回显数据
          galleryFileList: [],
          //增加关键字input显示状态
          newKeywordVisible: false,
          //关键字input数据
          newKeyword: '',
          //关键字列表
          keywords: [],
          //所属分类联级选择器数据
          categoryList: [],
          //所属品牌商列表
          brandList: [],
          //商品规格选择状态值
          multipleSpec: false,
          //商品规格列表数据
          specifications: [],
          //设置规格模态框状态值
          specVisible: false,
          // 设置规格表单数据
          specForm: {
              specification: '',
              value: '',
              picUrl: ''
          },
          // 设置规格表单校验
          specRules: {
            specification : [{
              required: true,
              message: '专题标题不能为空',
              trigger: 'blur'
            }],
          },
          //商品库存列表数据
          products: [{id:0,specifications:['标准'],price:0,number:0,url:''}],
          //货品规格状态值
          productVisiable: false,
          // 货品规格表单数据
          productForm:{
            id:0,
            specifications: ['标准'],
            price: 0,
            number: 0,
            url: ''
          },
          //商品参数表格数据
          attributes: [],
          //商品参数模态框状态值
          attributeVisiable: false,
          //商品参数表单数据
          attributeForm: {
            attribute: '',
            value: ''
          },
          //副文本框初始化属性
          editorInit: {
            language: 'zh_CN',
            convert_urls: false,
            height: 500,
            plugins: [
              'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
            ],
            toolbar: [
              'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
              'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'
            ],
            // 图片上传钩子
            images_upload_handler: function (blobInfo, success, failure) {
              const formData = new FormData()
              formData.append('file', blobInfo.blob())
              createStorage(formData)
                .then(res => {
                  success(res.data.data.url)
                })
                .catch(() => {
                  failure('上传失败，请重新上传')
                })
            }
          },
        }
      },
      created() {
        // 数据初始化
        this.init();
        this.specifications = [{
          specification: '规格',
          value: '标准',
          picUrl: ''
        }]
      },
      methods: {
        init() {
          if(this.$route.query.id == null){
            return;
          }
          const goodsId = this.$route.query.id;
          detailGoods(goodsId).then(res => {
            this.dataForm = res.data.data.goods;
            this.specifications = res.data.data.specifications;
            this.products = res.data.data.products;
            this.attributes = res.data.data.attributes;
            //宣传画廊数据回显
            this.galleryFileList = [];
            for(var i = 0;i<this.dataForm.gallery.length;i++){
              this.galleryFileList.push({url:this.dataForm.gallery[i]});
            }
            //关键字回显
            const keywords = res.data.data.goods.keywords;
            if(keywords !== null){
              this.keywords = keywords.split(',');
            }
          })
  
  
          //查询商品分类以及品牌商
          listCatAndBrand().then(res => {
            this.categoryList = res.data.data.categoryList;
            this.brandList = res.data.data.brandList;
          })
        },
        //所属分类change钩子
        handleCategoryGhange(value){
          console.log(value);
          this.dataForm.categoryId = value[value.length -1];
        },
        //取消商品上架
        handleCancel() {
          this.$router.push({path:'/goods/index'})
        },
        //图片上传成功后执行的方法
        handleAvatarSuccess(res, file) {
          this.dataForm.picUrl = res.data.url
        },
        //图片上传成功前执行的方法
        beforeAvatarUpload(file) {
          // const isJPG = file.type === 'image/jpeg'; 
          // const isLt2M = file.size / 1024 / 1024 < 2;
          // if (!isJPG) {
          //   this.$message.error('上传头像图片只能是 JPG 格式!');
          // }
          // if (!isLt2M) {
          //   this.$message.error('上传头像图片大小不能超过 2MB!');
          // }
          // return isJPG && isLt2M;
        },
        // 宣传画廊成功上传钩子函数
        handleGalleryUrl(res, file, fileList) {
          if(res.errno === 0){
            this.dataForm.gallery.push(res.data.url);
          }
        },
        // 宣传画廊删除图片 
        handleRemove(file, fileList) {
          console.log(file, fileList);
          for(var i = 0;i<this.dataForm.gallery.length;i++){
            var url;
            if(file.response === undefined){
              url = file.url
            }else{
              url = file.response.data.url.replace(/localhost/, '192.168.207.2')
            }
            if(this.dataForm.gallery[i] === url){
              this.dataForm.gallery.splice(i,1);
            }
          }
        },
        // 增加关键字函数
        showInput() {
          this.newKeywordVisible = true;
          this.$nextTick(_ => {
            //点击新增按钮，完成input输入聚焦
            this.$refs.newKeywordInput.$refs.input.focus();
          })
        },
        //关键字input的失焦函数
        handleInputConfirm() {
          const newKeyword = this.newKeyword;
          if (newKeyword) {
            this.keywords.push(newKeyword);
            this.dataForm.keywords = this.keywords.toString();
          }
          this.newKeywordVisible = false;
          this.newKeyword = ''
        },
        //关键字删除
        handleClose(tag) {
          this.keywords.splice(this.keywords.indexOf(tag), 1);
          this.dataForm.keywords = this.keywords.toString();
        },
        //商品规格监听方法
        specChange(val) {
          if (val === false) {
            this.specifications = [{
              specification: '规格',
              value: '标准',
              picUrl: ''
            }]
            this.products = [{id:'',specifications:['标准'],price:0,number:0,url:''}]
  
          } else {
            this.specifications = [];
            this.products = [];
          }
        },
        //添加商品规格
        handleSpecificationShow() {
          this.specForm = {
              specification: '',
              value: '',
              picUrl: ''
          };
          this.specVisible = true;
        },
        //确定添加商品规格
        handleSpecificationAdd(){
          this.specifications.push(this.specForm);
          if(this.products.length == 0){
            this.products = [{id:0,specifications:[],price:0,number:0,url:''}];
            this.products[0].specifications.push(this.specifications[0].specification);
          }else{
            this.products[0].specifications.push(this.specForm.specification);
          }
          
          this.specVisible = false;
        },
        //商品规格表格数据删除
        specificationsDelete(row) {
            if(this.specifications.length != 1){
              this.specifications.splice(this.specifications.indexOf(row),1);
              this.products[0].specifications.splice(this.products[0].specifications.indexOf(row.specification),1);
            }else{
              this.specifications.splice(this.specifications.indexOf(row),1);
              this.products = [];
            }
            
        },
        //规格图片上传成功后执行的方法
         handleSpecSuccess(res, file) {
          this.specForm.picUrl = res.data.url
        },
        //设置商品规格
        handleProductShow(row){
          this.productForm = Object.assign({},row);
          this.productVisiable = true;
        },
        //货品规格图片上传成功后执行的方法
        handleProductSuccess(res, file) {
          this.productForm.url = res.data.url
        },
        //货品规格确定修改
        handleProductEdit(){
            for(var i=0;i<this.products.length;i++){
              const v = this.products[i];
              if(v.id === this.productForm.id){
                //可以在数组中添加/删除元素
                // splice(从何处添加/删除，删除的个数，添加到数组新元素)
                this.products.splice(i,1,this.productForm);
                break;
              }
            }
            this.productVisiable = false;
        },
  
        //商品参数添加
        handleAttributeShow(){
          this.attributeForm = {
            attribute: '',
            value: '',
          }
          this.attributeVisiable = true;
        },
        //商品参数删除
        handleAttributeDelete(row){
           const index = this.attributes.indexOf(row);
           this.attributes.splice(index,1);
        },
        //商品参数确定添加
        handleAttributeAdd(){
          this.attributes.unshift(this.attributeForm);
          this.attributeVisiable = false;
        },
        //确定新增商品
        createData() {
          const finalGoods = {
            goods: this.dataForm,
            specifications: this.specifications,
            products: this.products,
            attributes: this.attributes
          }
          editGoods(finalGoods).then(res => {
            this.$notify.success({
              title: '成功',
              message: res.data.errmsg
            })
            //跳转回表格页面
            this.$router.push({path:'/goods/index'})
          }).catch(res => {
            this.$notify.error({
              title: '失败',
              message: res.data.errmsg
            })
          })
        },
      }
    }
  
  </script>
  <style>
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
  
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
  
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
  
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  
    .el-card {
      margin-bottom: 20px;
    }
  
    .input-new-keyword {
      width: 90px;
      margin-left: 10px;
      vertical-align: bottom;
    }
  
  </style>
  <style scoped>
  </style>
  